<template>
  <div id="cesiumContainer" style="width: 100%; height: 100vh; position: relative;">
    <!-- 控制按钮 -->
    <div
        style="
        position: absolute;
        top: 10px;
        left: 10px;
        z-index: 9999;
        display: flex;
        flex-wrap: wrap;
        gap: 5px;
        max-width: 90vw;
      "
    >
      <!-- 基础图层 -->
      <button class="button_a" @click="switchToImagery()">影像</button>
      <button class="button_a" @click="switchToVector()">矢量</button>
      <button class="button_a" @click="switchToVector()">地形</button>

      <!-- 视图控制 -->
      <button class="button_a" @click="toggleControls">
        {{ showControls ? '隐藏控件' : '显示控件' }}
      </button>

      <!-- 飞行定位 -->
      <button class="button_a" @click="flyToShenZhen()">飞往深圳</button>
<!--      <button class="button_a" @click="flyToCUIT()">飞往CUIT</button>-->

      <!-- 绘制功能 -->
      <button class="button_a" @click="drawPoint()">点</button>
      <button class="button_a" @click="drawLabel()">文字</button>
      <button class="button_a" @click="drawPolyline()">线</button>
      <button class="button_a" @click="drawPolygon()">面</button>
      <button class="button_a" @click="drawBox()">体</button>

      <!-- 清除 -->
      <button class="button_a clear-btn" @click="clearAllDrawings()">清除所有</button>
    </div>
    <NavigationBar />
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue';
import * as Cesium from 'cesium';
import NavigationBar from './NavigationBar.vue';

let viewer = null;
let vecLayer = null;
let cvaLayer = null;
let imgLayer = null;
let ciaLayer = null;
const showControls = ref(true);
const drawnEntities = ref([]); // 存储所有绘制的实体

onMounted(() => {
  Cesium.Ion.defaultAccessToken =
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyZmY3MGY5OS02NzczLTRmMjctYThkYi04NDExMGQxMDM1OGUiLCJpZCI6MzQ1Nzk1LCJpYXQiOjE3NTkyMDMwODJ9.QIySdS-vsDTb8pYtFGTSEueLHuhh3Ft3vjw1Q-wLY1Q';

  viewer = new Cesium.Viewer('cesiumContainer', {
    imageryProvider: false,
    homeButton: true,
    sceneModePicker: true,
    baseLayerPicker: true,
    navigationHelpButton: true,
    animation: true,
    timeline: true,
    fullscreenButton: true,
    vrButton: false,
    infoBox: true,
  });

  viewer._cesiumWidget._creditContainer.style.display = 'none';

  const webKey = 'e0544d1d5d87cd63d1f2d0338830974c';

  // === 矢量底图 + 注记 ===
  vecLayer = new Cesium.WebMapTileServiceImageryProvider({
    url: `http://{s}.tianditu.gov.cn/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=${webKey}`,
    layer: 'tdtVecBasicLayer',
    style: 'default',
    format: 'tiles',
    tileMatrixSetID: 'w',
    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    maximumLevel: 18,
    credit: new Cesium.Credit('天地图'),
  });

  cvaLayer = new Cesium.WebMapTileServiceImageryProvider({
    url: `http://{s}.tianditu.gov.cn/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=${webKey}`,
    layer: 'tdtAnnoLayer',
    style: 'default',
    format: 'image/jpeg',
    tileMatrixSetID: 'w',
    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    maximumLevel: 18,
    credit: new Cesium.Credit('天地图'),
  });

  // === 影像底图 + 注记 ===
  imgLayer = new Cesium.WebMapTileServiceImageryProvider({
    url: `http://{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=${webKey}`,
    layer: 'tdtBasicLayer',
    style: 'default',
    format: 'tiles',
    tileMatrixSetID: 'w',
    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    maximumLevel: 18,
    credit: new Cesium.Credit('天地图'),
  });

  ciaLayer = new Cesium.WebMapTileServiceImageryProvider({
    url: `http://{s}.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=${webKey}`,
    layer: 'tdtAnnoLayer',
    style: 'default',
    format: 'image/jpeg',
    tileMatrixSetID: 'w',
    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    maximumLevel: 18,
    credit: new Cesium.Credit('天地图'),
  });

  // 默认加载影像图层
  viewer.imageryLayers.addImageryProvider(imgLayer);
  viewer.imageryLayers.addImageryProvider(ciaLayer);
});

onBeforeUnmount(() => {
  if (viewer && !viewer.isDestroyed()) {
    viewer.destroy();
    viewer = null;
  }
});

// ===== 图层切换 =====
function switchToImagery() {
  while (viewer.imageryLayers.length > 0) {
    viewer.imageryLayers.remove(viewer.imageryLayers.get(0), true);
  }
  viewer.imageryLayers.addImageryProvider(imgLayer);
  viewer.imageryLayers.addImageryProvider(ciaLayer);
}

function switchToVector() {
  while (viewer.imageryLayers.length > 0) {
    viewer.imageryLayers.remove(viewer.imageryLayers.get(0), true);
  }
  viewer.imageryLayers.addImageryProvider(vecLayer);
  viewer.imageryLayers.addImageryProvider(cvaLayer);
}

// ===== 控件显隐 =====
function toggleControls() {
  if (showControls.value) {
    hideAllControls();
  } else {
    showAllControls();
  }
  showControls.value = !showControls.value;
}

function hideAllControls() {
  if (!viewer || viewer.isDestroyed()) return;
  const container = viewer.container;
  const selectors = [
    '.cesium-home-button',
    '.cesium-scene-mode-picker',
    '.cesium-base-layer-picker',
    '.cesium-navigation-help-button',
    '.cesium-animation-widget',
    '.cesium-timeline-widget',
    '.cesium-fullscreen-button',
    '.cesium-viewer-toolbar',
    '.cesium-viewer-bottom',
  ];
  selectors.forEach((sel) => {
    const el = container.querySelector(sel);
    if (el) el.style.display = 'none';
  });
}

function showAllControls() {
  if (!viewer || viewer.isDestroyed()) return;
  const container = viewer.container;

  const map = {
    '.cesium-home-button': 'block',
    '.cesium-scene-mode-picker': 'block',
    '.cesium-base-layer-picker': 'block',
    '.cesium-navigation-help-button': 'block',
    '.cesium-animation-widget': 'block',
    '.cesium-timeline-widget': 'block',
    '.cesium-fullscreen-button': 'block',
    '.cesium-viewer-toolbar': 'flex',
    '.cesium-viewer-bottom': 'block',
  };

  for (const [sel, display] of Object.entries(map)) {
    const el = container.querySelector(sel);
    if (el) el.style.display = display;
  }
}

// ===== 飞行功能 =====
function flyToShenZhen() {
  if (!viewer || viewer.isDestroyed()) return;
  const destination = Cesium.Cartesian3.fromDegrees(114.05, 22.5, 5000);
  viewer.camera.flyTo({
    destination: destination,
    orientation: {
      heading: Cesium.Math.toRadians(0),
      pitch: Cesium.Math.toRadians(-30),
      roll: 0,
    },
    duration: 3.0,
  });
}

function flyToCUIT() {
  if (!viewer || viewer.isDestroyed()) return;
  const destination = Cesium.Cartesian3.fromDegrees(
      103.98728599780004,
      30.576285364916018,
      800
  );
  viewer.camera.flyTo({
    destination: destination,
    orientation: {
      heading: Cesium.Math.toRadians(0),
      pitch: Cesium.Math.toRadians(-45),
      roll: 0,
    },
    duration: 3.0,
  });
}

// ===== 绘制功能 =====
// 点
function drawPoint() {
  if (!viewer || viewer.isDestroyed()) return;
  const point = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(114.05,22.5),
    point: {
      pixelSize: 20,
      color: Cesium.Color.BLUE,
    },
  });
  drawnEntities.value.push(point);
  viewer.zoomTo(point);
}

// 文字
function drawLabel() {
  if (!viewer || viewer.isDestroyed()) return;
  const label = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(114.05,22.5),
    label: {
      text: '深圳',
      font: '24px sans-serif',
      fillColor: Cesium.Color.YELLOWGREEN,
      showBackground: true,
      backgroundColor: Cesium.Color.BLACK.withAlpha(0.6),
      pixelOffset: new Cesium.Cartesian2(0, -20),
    },
  });
  drawnEntities.value.push(label);
}

// 线
function drawPolyline() {
  if (!viewer || viewer.isDestroyed()) return;
  const polyline = viewer.entities.add({
    polyline: {
      positions: Cesium.Cartesian3.fromDegreesArray([
        114.053, 22.520,
        114.055, 22.521,
        114.057, 22.522,
      ]),
      width: 8,
      material: Cesium.Color.RED,
    },
  });
  drawnEntities.value.push(polyline);
}

// 面
function drawPolygon() {
  if (!viewer || viewer.isDestroyed()) return;
  const polygon = viewer.entities.add({
    polygon: {
      hierarchy: Cesium.Cartesian3.fromDegreesArray([
        121.47, 31.23,
        121.476, 31.23,
        121.476, 31.23,
        121.47, 31.23,
      ]),
      material: Cesium.Color.fromRandom({ alpha: 0.6 }),
      outline: true,
      outlineColor: Cesium.Color.WHITE,
      height: 0,
    },
  });
  drawnEntities.value.push(polygon);
}

// 体
function drawBox() {
  if (!viewer || viewer.isDestroyed()) return;
  const box = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(114.0537076388042,22.52456797249851, 500),
    box: {
      dimensions: new Cesium.Cartesian3(800, 500, 8000),
      material: Cesium.Color.ORANGE.withAlpha(0.8),
    },
  });
  drawnEntities.value.push(box);
}

// ===== 清除所有绘制 =====
function clearAllDrawings() {
  if (!viewer || viewer.isDestroyed()) return;
  drawnEntities.value.forEach((entity) => {
    viewer.entities.remove(entity);
  });
  drawnEntities.value = [];
}
</script>

<style scoped>
#cesiumContainer {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.button_a {
  background-color: #b856d8;
  color: white;
  border: solid 1px white;
  padding: 6px 12px;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  white-space: nowrap;
}

.button_a:hover {
  background-color: #6b1aae;
}

.button_a:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.clear-btn {
  background-color: #e74c3c !important;
}

.clear-btn:hover {
  background-color: #c0392b !important;
}
</style>